/*
 * @Author: ReinerLau lk850593913@gmail.com
 * @Date: 2022-10-20 13:50:41
 * @LastEditors: ReinerLau lk850593913@gmail.com
 * @LastEditTime: 2023-02-16 15:28:08
 * @FilePath: \v2.0.0\src\views\patroling\composables\useWebsocket.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { getToken } from "@/utils/auth.js";
import { onBeforeUnmount, ref } from "vue";

interface websocketCallback {
  onOpen?: (e?, options?) => void;
  onMessage: (e?, options?) => void;
  onError?: (e?, options?) => void;
  onClose?: (e?, options?) => void;
}

export default (options: websocketCallback) => {
  const { onOpen, onError, onMessage, onClose } = options;

  let websocket: WebSocket;

  function initWebsocket() {
    const token = getToken();
    websocket = new WebSocket(
      `ws://${window.location.host}${import.meta.env.VITE_WEBSOCKET_API}`,
      [token]
    );
    initCallback(websocket);
  }

  onBeforeUnmount(() => {
    close(websocket);
    clearTimeout(reconnectWebsocketSt.value);
  });

  function close(ws: WebSocket) {
    ws.close();
  }
  const reconnectWebsocketSt = ref(0);
  function reconnectWebsocket() {
    clearTimeout(reconnectWebsocketSt.value);
    reconnectWebsocketSt.value = window.setTimeout(() => {
      initWebsocket();
      reconnectWebsocket();
    }, 5 * 1000);
  }

  const callbackOptions = {
    reconnectWebsocketSt,
    reconnectWebsocket,
  };

  function initCallback(ws: WebSocket) {
    ws.onerror = onError ? (e) => onError(e, callbackOptions) : null;
    ws.onopen = onOpen ? (e) => onOpen(e, callbackOptions) : null;
    ws.onmessage = onMessage ? (e) => onMessage(e, callbackOptions) : null;
    ws.onclose = onClose ? (e) => onClose(e, callbackOptions) : null;
    window.onbeforeunload = () => close(ws);
  }

  initWebsocket();

  return {
    initWebsocket,
    reconnectWebsocket,
  };
};
